package com.lhweb.springsecurity.dataInit;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;

import com.lhweb.springsecurity.security.CustomJdbcDaoImpl;
import com.lhweb.springsecurity.security.SaltedUser;

/**
 * 将数据库密码进行sha加密
 * @author 2
 *
 */
public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private SaltSource saltSource;
	@Autowired
	private CustomJdbcDaoImpl customJdbcDaoImpl;
	
	public void encodePasswordTest(){
		getJdbcTemplate().query("select username,password from users",new RowCallbackHandler(){

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);
				
				List<UserDetails> users = customJdbcDaoImpl.loadUsersByUsername(username);
				System.out.println("salt:"+saltSource.getSalt(users.get(0)));
				String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(users.get(0)));
				getJdbcTemplate().update("update users set password = ? where username = ?",encodedPassword,username);
			}
		});
	}
	
	
}
